package net.j4love.mybatis.kit.plugin;

import net.j4love.mybatis.kit.CommonObjectCache;
import net.j4love.mybatis.kit.sql.SQLParserUtils;
import net.j4love.mybatis.kit.sql.TableCommand;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.util.List;
import java.util.Properties;
import java.util.Set;


@Intercepts({
        @Signature(
                type = Executor.class ,
                method = "update" ,
                args = {MappedStatement.class , Object.class })}
)
public class UpdateDetectionInterceptor implements Interceptor {

    private static final Log LOG = LogFactory.getLog(UpdateDetectionInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = ms.getBoundSql(invocation.getArgs()[1]);
        String dbType = (String) CommonObjectCache.get(CommonObjectCache.DATABASE_TYPE_KEY);
        Set<String> tables = SQLParserUtils.getTableNames(boundSql.getSql(), dbType);
        BoundThreadUpdatedTableUtils.append(tables);

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return target;
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
